package com.acme.bankapp.service.bank.network;

import com.acme.bankapp.service.bank.BankReport;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;

public class BankServer {
    ServerSocket providerSocket;
    Socket connection = null;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;

    public BankServer() {
    }

    public void startServer() {
        try {
            providerSocket = new ServerSocket(2013, 10);
            System.out.printf("Waiting for connection\n");
            connection = providerSocket.accept();
            System.out.printf("Connection received from %s\n", connection.getInetAddress().getHostName());
            out = new ObjectOutputStream(connection.getOutputStream());
            out.flush();
            in = new ObjectInputStream(connection.getInputStream());
            sendMessage("Connection successful");
            do {
                try {
                    message = (String) in.readObject();

                    System.out.printf("client>%s\n", message);
                    StringTokenizer stoken = new StringTokenizer(message, " ");
                    if (stoken.hasMoreTokens()) {
                        switch (stoken.nextToken()) {
                            case "get":
                                if (stoken.hasMoreTokens()) {
                                    message = BankReport.searchClient(Integer.parseInt(stoken.nextToken()));
                                } else {
                                    message = "Invalid parameters";
                                }
                                sendMessage(message);
                                break;
                        }
                    }

                } catch (ClassNotFoundException classnot) {
                    System.err.printf("Data received in unknown format\n");
                }
            } while (!message.equals("bye"));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
                providerSocket.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    void sendMessage(final String msg) {
        try {
            out.writeObject(msg);
            out.flush();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

//    public static void main(final String args[]) {
//        BankServer server = new BankServer();
//        while (true) {
//            server.run();
//        }
//    }
}

